import pandas as pd
import Core.Gadget as Gadget
import Core.MongoDB as MongoDB
import datetime

def Xueqiu_followers(symbol,datetime1,datetime2):
    Data_xueqiu = database.find("Text", "XueqiuFollowers", datetime1, datetime2, query={"Symbol": symbol})
    if len(Data_xueqiu)>0:
        Stock_followers = Data_xueqiu[-1]
        return(Stock_followers["Followers"])
    else:
        return(None)

def StockList(database, datetime2, ipo_datetime1 = None, ipo_datetime2 = None, IPO_date = False):


    trades = database.find("Instruments", "Stock")
    symbols = []
    for trade in trades:
        if IPO_date == True:
            if trade["IPO_Date"] < ipo_datetime1 or trade["IPO_Date"] > ipo_datetime2:
                continue
        if trade["DateTime2"]< datetime2:
            continue
        symbol = trade["Symbol"]
        symbols.append(symbol)
        #print(symbol,"满足上市时间股票")
    return symbols

def MaxRetracement(timeserise):
    # 读取sheet1中的内容，存放在data中，数据类型为DataFrame
    df = pd.DataFrame(timeserise, columns=['closeprice'])
    Max = df.max()
    Min = df.min()
    drawback = (Max - Min) / Max
    a = list(drawback)
    b = list(Min)
    drawback = a[0]
    Min = b[0]
    return(drawback, Min)

def screening_condition_followers(stock_list, xueqiu= 2500):
    list_after_screening = []
    for i in range(len(stock_list)):
        symbol = stock_list[i]
        followers = Xueqiu_followers(symbol, datetime1, datetime2)

        if followers is None:
            continue
        if followers < xueqiu:
            list_after_screening.append(symbol)
            # print(symbol, followers)
    return(list_after_screening)

def screening_condition_quotes(stock_list, datetime1, datetime2, years = 100 ,mv_limit = 800000000, min_fall = 0.5):
    list_after_screening = []
    for i in range(len(stock_list)):
        symbol = stock_list[i]
        if symbol == "000033.SZ":
            debug =1
        quotes = database.find("Quote", symbol + "_Time_86400_Bar", datetime1, datetime2)

        quote = quotes[len(quotes) - 1]
        Marketvalue = quote["Close"] * quote["Values"]["FreeFloatShares"]
        if Marketvalue < mv_limit:
            prices = []
            for i in range(len(quotes)):
                prices.append(quotes[i]["Close"]/quotes[i]["AdjFactor"])
            Maxretracement = MaxRetracement(prices)
            if Maxretracement[0] > min_fall: #and Maxretracement[1] == quote["Close"]:#最高点跌幅首超50%
                list_after_screening.append(symbol)
                #print(symbol,"满足筛选规则股票")



    return(list_after_screening)


from Core.Config import Config
config = Config()
database = config.DataBase()

datetime1 = datetime.datetime(2016, 3, 1)
datetime1 = Gadget.ToUTCDateTime(datetime1)
datetime2 = datetime.datetime(2018, 11, 15)
datetime2 = Gadget.ToUTCDateTime(datetime2)
ipo_datetime1 = datetime.datetime(2016, 3, 1)
ipo_datetime1 = Gadget.ToUTCDateTime(ipo_datetime1)
ipo_datetime2 = datetime.datetime(2017, 10, 31)
ipo_datetime2 = Gadget.ToUTCDateTime(ipo_datetime2)

stock_list = StockList(database,datetime2, ipo_datetime1,ipo_datetime2,True)#上市时间区间
debug = 1
mv_limit = 800000000
min_fall = 0.5
years = 100
stock_list_1 = screening_condition_quotes(stock_list,datetime1,datetime2,years, mv_limit, min_fall)#条件一：上市时间不满100年，通市值小于8亿，半年内跌幅超过50%
#stock_list_2 = screening_condition_quotes(stock_list,datetime1,datetime2,2)
stock_list_1_2 = screening_condition_followers(stock_list_1, 2500)#条件一：雪球关注度小于2500流
for i in range(len(stock_list_1_2)):
    print(stock_list_1_2[i],"满足雪球关注度股票")
#print(Gadget.ToDate(ipo_datetime1),"到",Gadget.ToDate(ipo_datetime2) ,"年间上市的, 流通盘小于" , mv_limit/100000000 ,"亿,且跌幅超过", min_fall*100 , "%的股票")
#for i in range(len(stock_list_1)):
    #print(stock_list_1[i])


